/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package goodenglish.interfaces.videoplay;

import goodenglish.domain.model.lexicon.NewWord;
import goodenglish.domain.model.subt.Subt;
import goodenglish.domain.model.subt.SubtSentence;
import goodenglish.infrastructure.Config;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.util.Duration;

/**
 * 字幕监视器
 * 
 * @author 关攀攀 panpan_001@126.com
 */
class SubtShowListener implements ChangeListener<Duration> {

	private MediaPane mediaControl;
	private long stime = -1;
	private long etime = -1;
	private Subt subt;

	public SubtShowListener(MediaPane mediaControl) {
		this.mediaControl = mediaControl;
		this.subt = mediaControl.subt;
	}

	public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
		mediaControl.updateValues();

		updateSubtViews();
	}

	public void updateSubtViews() {
		// 得到当前播放时间
		int currentTime = (int) Math.floor(mediaControl.mediaPlayer.getCurrentTime().toMillis());

		// 如果超出播放区间则取新字幕
		if (currentTime > etime || currentTime < stime || stime == -1) {
			SubtSentence sentence = subt.getCurrentSentence(currentTime);

			if (sentence == null) {
				return;
			}

			if (Config.PLAY_MODE.equals(PlayMode.DIRECT)) {
				StringBuffer explainBuffer = new StringBuffer();
				List<String> spells = subt.getNewWordSpells(sentence);
				List<NewWord> subtWords = subt.getLexicon().getNewWords(spells);
				for (NewWord subtWord : subtWords) {
					explainBuffer.append(subtWord.getSpell());
					explainBuffer.append(":");
					explainBuffer.append(subtWord.getShortExplain());
					explainBuffer.append("   ");
				}
				if (subtWords.size() > 0) {
					MediaGroup.subtViewLabel.setDisplayBackgroud(true);
					int studytime = subtWords.size() * 3;
					mediaControl.mediaPlayer.pause();
					for (int i = 0; i < studytime * 10; i++) {
						StringBuffer buffer = new StringBuffer();
						buffer.append(Integer.toString(studytime - i / 10));
						buffer.append("\r\n");
						buffer.append(explainBuffer);
						MediaGroup.subtViewLabel.displayForView(buffer.toString());
						try {
							Thread.sleep(100);
						} catch (InterruptedException ex) {
							Logger.getLogger(MediaPane.class.getName()).log(Level.SEVERE, null, ex);
						}
					}
					MediaGroup.subtViewLabel.setDisplayBackgroud(false);
					mediaControl.mediaPlayer.play();
				}

			}
			MediaGroup.subtViewLabel.displayForView(sentence.getEnStr());
			stime = sentence.getStime();
			etime = sentence.getEtime();

		}
	}
}
